package sdk.webview.fmc.com.fmcsdk.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

//import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.HashSet;
import java.util.Set;

import cn.jiguang.api.JCoreManager;
import cn.jiguang.api.utils.JCollectionAuth;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


/**
 * Created by ydm on 2017/8/17.
 * 极光推送设置的工具类
 */

public class JpushUtils {
    private TagAliasCallback callback;
    public static final int MSG_SET_ALIAS = 3;


    final char[] DIGITS =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                    'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                    'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
                    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                    'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

    StringBuffer sb_ = new StringBuffer();
    public SharedPreferences sharedPrefs;
    private Context context;
    private FMCLog logger;
    Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_SET_ALIAS:

                    // 调用 JPush 接口来设置别名。
                    Bundle bundle = (Bundle) msg.obj;
                    if (bundle == null) {
                        XLog.i("bundle为空");
                        return;
                    }
                    //别名
                    String alias = bundle.getString("alias");
                    //标签
                    String address = bundle.getString("address");
                    String buid = bundle.getString("build");

                    Set<String> set = new HashSet<>();
                    if (!TextUtils.isEmpty(address) && address.length() < 40) {
                        address = address.replace("/", "|").replace(":", "=");
                        set.add(address);
                    }
                    /**极光参数不识别中划线*/
                    if (buid.contains("-")) {
                        String s = buid.replace("-", "_");
                        set.add(s);
                    } else {
                        set.add(buid);
                    }
                    XLog.i("Set alias in handler.alias=" + alias + "账号:" + UserHelper.getUserName() + ",tag = " + set.toString(), context);

//                    JPushInterface.setAliasAndTags(context.getApplicationContext(),alias,callback);
                    JPushInterface.setAlias(context.getApplicationContext(), 1, alias);
                    break;
            }
        }
    };

    /**
     * 开启推送
     */
    public void startPush(final Context context) {
        this.context = context;
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        logger = FMCLog.getInstance(context);
        initJPush();
    }

    /**
     * 初始化极光推送
     */
    private void initJPush() {
        JPushInterface.resumePush(context.getApplicationContext());
        JPushInterface.setDebugMode(true);
//        JCollectionAuth.setAuth(context, false); // 后续初始化过程将被拦截


        //在init之前调用
        Bundle bundle = new Bundle();
        // 设置心跳30s，心跳间隔默认是4min50s
        bundle.putInt("heartbeat_interval", 30);
        JCoreManager.setSDKConfigs(context.getApplicationContext(), bundle);

        JPushInterface.init(context.getApplicationContext());
        JCollectionAuth.setAuth(context.getApplicationContext(), true); //如初始化被拦截过，将重试初始化过程
//        MiPushClient.getRegId(context);
//        XLog.i( "reg:"+MiPushClient.getRegId(context));

//        if (JPushInterface.isPushStopped(context.getApplicationContext())) {
//            JPushInterface.resumePush(context.getApplicationContext());
//        }

        Log.e("Jpush", "registerId--->" + JPushInterface.getRegistrationID(context));

        callback = new TagAliasCallback() {
            @Override
            public void gotResult(int code, String alias, Set<String> tags) {
                String logs;
                switch (code) {
                    case 0:
                        logs = "Set tag and alias success";
                        logger.info("MainActivity", logs);

                        break;
                    case 6002:
                        logs = "Failed to set alias and tags due to timeout. Try again after 20s.";
                        logger.info("MainActivity", logs);
                        // 延迟 20 秒来调用 Handler 设置别名
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, getJPushBundle()), 1000 * 10);
                        break;
                    default:
                        logs = "Failed with errorCode = " + code;
                }
                logger.info("MainActivity", logs);
                XLog.i("-------------JPUSH CODE = " + code, context);
            }
        };
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, getJPushBundle()));
    }


    private Bundle getJPushBundle() {
        if (!TextUtils.isEmpty(UserHelper.getUserId())) {
            Bundle bundle = new Bundle();
            //推送环境标识 一般是 _sit _dev 正式环境大多数为空
            String aliasStr = PreferencesHelper.getData(Constant.JPUSH_ALIAS);
            String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
            //领展项目此处用用户id转码后拼接imei加上环境标识作为别名alias
//            if (Constant.APP_NAME_LINK.equals(appName)) {
//                StringBuilder sBuilder = getUseridTo62();
//                bundle.putString("alias", sBuilder.toString() + "_" + Utility.getIMEI(context) + aliasStr);
//            }else {
            bundle.putString("alias", UserHelper.getUserId() + aliasStr);
//            }

            Log.e("Jpush", "alias--->" + UserHelper.getUserId() + aliasStr);

            bundle.putString("address", sharedPrefs.getString(Constant.BASE_ADDRESS_URL, ""));
            bundle.putString("build", sharedPrefs.getString(Constant.BUID, ""));
            return bundle;
        }
        return null;
    }

    private StringBuilder getUseridTo62() {
        long seq = Long.parseLong(UserHelper.getUserId());
        StringBuilder sBuilder = new StringBuilder();
        while (true) {
            int remainder = (int) (seq % 62);
            sBuilder.insert(0, DIGITS[remainder]);
            seq = seq / 62;
            if (seq == 0) {
                break;
            }
        }
        return sBuilder;
    }

}
